package org.tuproj.drujbapizza;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class PizzaMenuActivity extends Activity {

	private ListView pizzasList;
	private ArrayList<Pizza> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pizza_menu);
		list = new ArrayList<Pizza>();
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			String s ="";

			if (extras.getString("JSON_STRING")==null) {
				list = extras.getParcelableArrayList("CURRENT_PIZZA_LIST");
			} else {
				 s = extras.getString("JSON_STRING");
				list = createPizzaObjects(s);
			}
			Log.i("Result in Menu", s);
			ArrayList<String> titles = new ArrayList<String>();
			for (Pizza pizza : list) {
				titles.add(pizza.getName());
			}

			for (String str : titles) {
				Log.i("Titles", str);
			}

			pizzasList = (ListView) findViewById(R.id.pizzasList);
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(
					PizzaMenuActivity.this,
					android.R.layout.simple_list_item_1, titles);
			pizzasList.setAdapter(adapter);

			pizzasList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {

					String selectedFromList = (String) (pizzasList
							.getItemAtPosition(arg2));
					Log.i("Selected item", selectedFromList);

					Intent intent = new Intent(PizzaMenuActivity.this,
							PizzaDetailActivity.class);
					intent.putParcelableArrayListExtra("CURRENT_PIZZA_LIST",
							list);
					intent.putExtra("PIZZA_INDEX", arg2);
					startActivity(intent);

				}

			});

		}

	}

	private ArrayList<Pizza> createPizzaObjects(String jsonString) {
		ArrayList<Pizza> jsonList = new ArrayList<Pizza>();
		try {
			JSONArray responseArray = new JSONArray(jsonString);
			for (int i = 0; i < responseArray.length(); i++) {
				JSONObject currentObject = responseArray.getJSONObject(i);
				Pizza pizza = new Pizza();
				pizza.setId(currentObject.getInt("id"));
				pizza.setName(currentObject.getString("name"));
				pizza.setDescription(currentObject.getString("description"));
				pizza.setPrice(currentObject.getDouble("price"));
				Log.i("Object", pizza.toString());
				jsonList.add(pizza);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonList;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_pizza_menu, menu);
		return true;
	}

}
